layui.config({
    base: 'assets/layuiadmin/' //静态资源所在路径
}).extend({
    index: 'lib/index' //主入口模块
}).use(['index', 'tree', 'form'], function(){
    var $ = layui.$, tree = layui.tree, form = layui.form;

    var id = $('#id').val();
    var data = {'id': id};
    post('role/toEdit', data, false,function (data) {
        var role = data.role;
        if(role){
            $('#name').val(role.name);
            if(id != ''){
                $('#name').attr('readonly', tree)
            }
            $('#desc').text(role.desc);
            $("#orderId").val(role.orderId);
            if(role.status == 0){
                $('#status').prop('checked', true);
            }else{
                $('#status').prop('checked', false);
            }
            form.render();
        }

        //渲染树
        tree.render({
            id: 'permissionIds',
            elem: '#permissions',
            data: handleTree(data.trees, data.permissionIds),
            showCheckbox: true,  //展示复选框
            oncheck: function (obj) {   //复选框点击回调

            }
        });
    });

    //校验
    form.verify({
        'permission-verify': function (value, item) {
            var checkData = tree.getChecked('permissionIds');
            if(checkData.length <= 0){
                return '请至少选择一个权限';
            }
            var perminssionIds = JSON.stringify(getTreeIds(checkData));
            $("#permissionIds").val(perminssionIds);
        }
    });

    /**
     * 处理权限数据
     * @param trees
     * @param permissionIds
     * @returns {Array}
     */
    function handleTree(trees, permissionIds) {
        var result = [];
        trees.forEach(function (tree) {
            var obj = {
                id: tree.id,
                title: tree.name,
                checked: permissionIds.includes(tree.id),
                children: [],
                spread: true    //展开节点
            };
            if(tree.childrens.length > 0){
                obj.checked = false;
                obj.children = handleTree(tree.childrens, permissionIds);
            }
            result.push(obj);
        });
        return result
    }

    /**
     * 获取权限id集合
     * @param trees
     * @returns {Array}
     */
    function getTreeIds(trees) {
        var ids = [];
        trees.forEach(function (tree) {
            var id = tree.id;
            if(tree.children.length > 0){
                ids = ids.concat(getTreeIds(tree.children));
            }
            ids.push(id);
        });
        return ids;
    }

});